//
//  UIView+KModuleUI.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 ZHBen. All rights reserved.
//

#import "KMView.h"
#import <objc/runtime.h>
@implementation UIView (KModuleUI)

- (NSArray<MASConstraint *> *)kmLayoutList
{
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setKmLayoutList:(NSArray<MASConstraint *> *)kmLayoutList
{
    objc_setAssociatedObject(self, @selector(kmLayoutList), kmLayoutList, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (UIView<KMView> *)addToWrapper:(UIView<KMWrapperView> *)wrapper frame:(CGRect)frame spec:(NSString *)spec
{
    UIView<KMView> * view = nil;
    if ([self instancesRespondToSelector:@selector(initWithFrame:spec:)])
    {
        view = [[self alloc] initWithFrame:frame spec:spec];
    }
    else
    {
        view = [[self alloc] initWithFrame:frame];
    }
    [view addToWrapper:wrapper];
    return view;
}

- (void)addToWrapper:(UIView<KMWrapperView> *)wrapperView
{
    [wrapperView.kmView removeFromWrapper:wrapperView];
    [wrapperView.contentView addSubview:self];
    wrapperView.kmView = (UIView<KMView> *)self;
    if (![wrapperView.kmView respondsToSelector:@selector(useLayout)] || [wrapperView.kmView useLayout])
    {
        self.kmLayoutList = [self mas_updateConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(@(0));
        }];
        [wrapperView.contentView setNeedsUpdateConstraints];
    }
}

- (void)removeFromWrapper:(UIView<KMWrapperView> *)wrapperView
{
    [self.kmLayoutList makeObjectsPerformSelector:@selector(uninstall)];
    [self removeFromSuperview];
    wrapperView.kmView = nil;
}

@end

@implementation KModuleView

+ (NSString *)viewID
{
    return nil;
}

- (instancetype)initWithFrame:(CGRect)frame spec:(NSString *)spec
{
    if (self = [super initWithFrame:frame])
    {
        _spec = [spec copy];
    }
    return self;
}

@end
